/*
 * CAppStateClient.cpp
 *
 *  Created on: 25/12/2012
 *      Author: Dalton
 */
#include "CAppStateClient.h"
#include "CSurface.h"
#include <iostream>

bool sended_1 = false;
CAppStateClient CAppStateClient::instance;

CAppStateClient::CAppStateClient(){
	surface = NULL;
	connected = false;
	tcpClient = NULL;
	remoteip = NULL;
	font = NULL;
	textConnected = NULL;
	textReceived = NULL;
}

void CAppStateClient::onActivate(){
	if((surface = CSurface::onLoad(".//data/imgs/tela_cliente.png")) == NULL){
		return;
	}
	tcpClient = new CClientSocket();
	remoteip = new CIpAddress("192.168.0.198", 7777);
	font = TTF_OpenFont(".//data/fonts/tahoma.TTF", 18);
	textConnected = TTF_RenderText_Blended(font, "Conectado ao servidor!", {80,255,38});

}

void CAppStateClient::onDeactivate(){
	SDL_FreeSurface(surface);
	surface = NULL;
	SDL_FreeSurface(textConnected);
	textConnected = NULL;
	delete remoteip;
	delete tcpClient;

}

void CAppStateClient::sendMsg(){
	if(connected){
		if (!sended_1) {
			char buffer[10];
			buffer[0] = 'k';
			buffer[1] = 'r';
			buffer[2] = 'a';
			buffer[3] = 'l';
			buffer[4] = 'h';

			msg.LoadBytes(buffer, 5);
			msg.finish();
			tcpClient->Send(msg);
			sended_1 = true;
		}
	}
}

void CAppStateClient::onLoop() {
	if (!connected) {
		if (tcpClient->Connect(*remoteip)) {
			if (tcpClient->Ok()) {
				textReceived = TTF_RenderText_Blended(font, "Connectado!", {80,255,38});
				connected = true;
			}
		}
	} else {
		//if connected, checks the socket for messages ready to be read
		if (tcpClient->Ready()) {
			// if there is a message, try to receive it. In case of disconnection, the TCP protocol sends
			// a message with no bytes
			if (tcpClient->Receive(msg)) {
				//if there is a valid message, we can set the grid and player status
				char text[MSG_MAX_LENGTH];
				msg.UnLoadBytes(text);
				SDL_FreeSurface(textReceived);
				textReceived = NULL;
				textReceived = TTF_RenderText_Blended(font, text, {80,255,38});
				sendMsg();
			} else {
				connected = false;
			}

		}

	}

}


void CAppStateClient::onRender(SDL_Surface* surfDisplay){
	if(surface){
		CSurface::onDraw(surfDisplay, surface,0,0);
	}
	if(connected){
		CSurface::onDraw(surfDisplay, textConnected,737,81);
		CSurface::onDraw(surfDisplay, textReceived,164,421);
	}
}

CAppStateClient* CAppStateClient::getInstance(){
	return &instance;
}
